package net.expectx.pay.merchant.controller;


import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.expectx.common.single.base.BaseResult;
import net.expectx.common.single.base.BaseResultConstants;
import net.expectx.common.single.util.Md5Util;
import net.expectx.common.single.util.RedisUtil;
import net.expectx.common.single.util.formatter.MessageFormatter;
import net.expectx.pay.dao.bean.*;
import net.expectx.pay.merchant.common.AdminConstants;
import net.expectx.pay.merchant.common.AdminResult;
import net.expectx.pay.merchant.common.BaseController;
import net.expectx.pay.rpc.api.MerchantApplicationService;
import net.expectx.pay.rpc.api.MerchantUserService;
import net.expectx.pay.rpc.api.PaymentChannelService;
import net.expectx.pay.rpc.api.PermissionUserService;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Array;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 单点登录管理
 *
 * @author jianhun
 * @date 2018/5/17
 */
@Controller
@RequestMapping("/sso")
@Api(value = "单点登录管理", description = "单点登录管理")
public class SsoController extends BaseController {

    private static final Logger LOGGER = Logger.getLogger(SsoController.class);
    /**
     * code key
     */



    @Autowired
    PermissionUserService permissionUserService;

    @Autowired
    MerchantUserService merchantUserService;

    @Autowired
    PaymentChannelService paymentChannelService;

    @Autowired
    MerchantApplicationService merchantApplicationService;


    @ApiOperation(value = "登录")
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login(HttpServletRequest request) {
        LOGGER.info(MessageFormatter.format("-----------------------{}-------------------------------", "进入登录"));
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        MerchantUser merchantUser = (MerchantUser) session.getAttribute("merchantUser");
        if (null!=merchantUser) {
            String backUrl = request.getParameter("backurl");
            if (StringUtils.isBlank(backUrl)) {
                backUrl = "/";
            } else {
            }
            StringBuffer sb = new StringBuffer("redirect:").append(backUrl);
            return sb.toString();
        }
        return "login";


    }

    @ApiOperation(value = "登录")
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public Object login(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String rememberMe = request.getParameter("rememberMe");
        String vercode = request.getParameter("vercode");

        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        MerchantUser merchantUser=(MerchantUser) session.getAttribute("merchantUser");
        if (null==merchantUser) {
            if (vercode.toLowerCase().equals(session.getAttribute("KAPTCHA_SESSION_KEY").toString().toLowerCase())){
                // 使用shiro认证
                UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
                try {
                    if (StringUtils.isNotEmpty(rememberMe)) {
                        usernamePasswordToken.setRememberMe(true);
                    } else {
                        usernamePasswordToken.setRememberMe(false);
                    }
                    subject.login(usernamePasswordToken);
                } catch (UnknownAccountException e) {
                    return new AdminResult(Boolean.FALSE, AdminConstants.FAILE, "帐号不存在！",null);
                } catch (IncorrectCredentialsException e) {
                    return new AdminResult(Boolean.FALSE, AdminConstants.FAILE, "密码错误！",null);
                } catch (LockedAccountException e) {
                    return new AdminResult(Boolean.FALSE, AdminConstants.FAILE, "帐号已锁定！",null);
                }
            }else{
                return new AdminResult(Boolean.FALSE, AdminConstants.FAILE, "验证码错误！",null);
            }
        }

        // 回跳登录前地址
        String backurl = request.getParameter("backurl");
        if (StringUtils.isBlank(backurl)) {
        }

        return new AdminResult(Boolean.TRUE,BaseResultConstants.SUCCESS, backurl);
    }



    @ApiOperation(value = "退出登录")
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String logout(HttpServletRequest request) {

        /**
         * shiro退出登录
         */
        SecurityUtils.getSubject().logout();
        /**
         * 跳回原地址
         */
        String redirectUrl = request.getHeader("Referer");
        if (null == redirectUrl) {
            redirectUrl = "/";
        }

        StringBuffer sb = new StringBuffer("redirect:").append(redirectUrl);
        return sb.toString();

    }

    @ApiOperation(value = "注册")
    @RequestMapping(value = "/register", method = RequestMethod.GET)
    public String register() {
        return "register";
    }


    @ApiOperation(value = "注册")
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    @ResponseBody
    public Object register(MerchantUser merchantUser){
        MerchantUserExample merchantUserExample = new MerchantUserExample();
        MerchantUserExample.Criteria criteria = merchantUserExample.createCriteria();
        criteria.andIsDeletedEqualTo(AdminConstants.NO);
        criteria.andEmailEqualTo(merchantUser.getEmail());
        List<MerchantUser> merchantUsers = merchantUserService.selectByExample(merchantUserExample);
        if (merchantUsers.size()==0){
            SimpleDateFormat simpleDateFormat;
            simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
            Date date = new Date();
            String str = simpleDateFormat.format(date);
            Random random = new Random();
            int ranMum = (int) (random.nextDouble() * (99999 - 10000 + 1)) + 10000;
            String merchantNo = str+ranMum ;

            merchantUser.setMerchantNo(merchantNo);
            merchantUser.setGmtCreate(System.currentTimeMillis());
            merchantUser.setGmtModified(System.currentTimeMillis());
            merchantUser.setIsDeleted((byte) 0);
            merchantUser.setIsLocked((byte) 0);
            merchantUser.setSalt(UUID.randomUUID().toString().toLowerCase().replace("-",""));
            merchantUser.setPassword(Md5Util.md5(merchantUser.getPassword()+merchantUser.getSalt()));

            BaseResult baseResult = merchantUserService.insertSelective(merchantUser);
            if (baseResult.isSuccess()){
                PaymentChannelExample paymentChannelExample = new PaymentChannelExample();
                paymentChannelExample.createCriteria().andIsDeletedEqualTo(AdminConstants.NO);
                List<PaymentChannel> paymentChannels = paymentChannelService.selectByExample(paymentChannelExample);
                List ids = new ArrayList();
                for (PaymentChannel paymentChannel : paymentChannels) {
                    ids.add(paymentChannel.getId()+"");
                }
                String idsStr = String.join(",", ids);
                String agentNo = merchantNo+"001";
                MerchantApplication merchantApplication = new MerchantApplication();
                merchantApplication.setMerchantNo(merchantNo);
                merchantApplication.setAgentNo(agentNo);
                merchantApplication.setName("我的第一个应用");
                merchantApplication.setScene("1");
                merchantApplication.setType("1");
                merchantApplication.setIntroduction("第一个应用");
                merchantApplication.setGmtCreate(System.currentTimeMillis());
                merchantApplication.setGmtModified(System.currentTimeMillis());
                merchantApplication.setIsDeleted(AdminConstants.NO);
                merchantApplication.setPaymentChannel(idsStr);
                if (merchantApplicationService.insertSelective(merchantApplication).isSuccess()){
                    return  new AdminResult(true);
                }
                MerchantUserExample merchantUserExample1 = new MerchantUserExample();
                merchantUserExample1.createCriteria().andIsDeletedEqualTo(AdminConstants.NO).andEmailEqualTo(merchantUser.getEmail());
                merchantUserService.deleteByExample(merchantUserExample1);
                return new AdminResult(false,200,"注册失败","");
            }
            return new AdminResult(false,200,"注册失败","");
        }
        return  new AdminResult(false,200,"用户已存在","");
    }

}
